/*************************************************************************
	> File Name: pthread_attr.c
	> Author: Angel Criss
	> Mail: abbytsing@gmail.com 
	> Created Time: 六  7/19 14:35:03 2014
 ************************************************************************/
/*
 * 实验证明 void *ret 和 pthread_exit(ret)的搭配
 * 和 return (void *)strlen(line) 效果相同
 * 另外对于设置了attr的线程 main函数中的两个块注释
 * 作用相同
 *
 * 由于书上对pthread_attr介绍几乎可以忽略不计,所以
 * 暂时先写成这样。。
 */

#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>

void err(int return_status,char *ERR){
    if(return_status!=0)
    {
        perror(ERR);
        exit(return_status);
    }
}

void *func(void *arg){
    int i;
    char *line=(char *)arg;
    void *ret; // return vslue for pthread_join use
    printf("%s",line);
    for(i=0;i<10;i++)
    {
        printf("%d\n",i);
        sleep(1);
    }
    //return (void *)strlen(line);
    pthread_exit(ret); 
}

int main(int argc,char *argv[]){
    pthread_t pd; // pd: P threa D
    int s; // status
    pthread_attr_t attr;
    void *res;

    s=pthread_attr_init(&attr);
        err(s,"attr_init");
/*    
    s=pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
        err(s,"attr_detached");
*/
    s=pthread_create(&pd,&attr,func,"start pthread\n");
        err(s,"pthread_create");
/*
    s=pthread_detach(pd);
        err(s,"pthread_detach");
*/
    s=pthread_attr_destroy(&attr);
        err(s,"attr_destroy");

    printf("sleep in main function for 15s\n");
    sleep(15);

    s=pthread_join(pd,&res);
    if(s!=0)
        printf("join failed\n");
    else
        printf("the init 'attr' has been destroyed\n");
    printf("\e[35mThe pthread exit value is %ld \n",(long)res);

    exit(EXIT_SUCCESS);
}
